package com.xm.controller.mobile;

import com.xm.util.JSONMsg;
import com.xm.util.StringUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @Description 公共模块（文件上传）
 * @Author semstouch
 * @Date 2017/4/28
 **/
@Controller
@RequestMapping("/m/common")
public class CommonMobileController {
    private JSONMsg jsonMsg;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public JSONMsg uploadPhone(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
        jsonMsg= new JSONMsg();
        String path=uploadFile(file, request);
        jsonMsg.setStatus(true);
        jsonMsg.setMsg(path);
        return jsonMsg;
    }

    /**
     * 上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    private String  uploadFile(MultipartFile file,HttpServletRequest request) throws IOException {
        String path=request.getSession().getServletContext().getRealPath("upload");
        String fileName=file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        String newFileName = StringUtils.getNowTime().toString()+rannum+suffix;
        File targetFile=new File(path,newFileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);
        Thumbnails.of(targetFile.getPath()).scale(1f).outputQuality(0.25f).toFile(targetFile.getPath());
        return  "/upload/"+newFileName;
    }

}
